﻿Imports System
Imports System.Collections
Imports System.Runtime.Serialization

Namespace System.Workflow.ComponentModel.Serialization
    Friend NotInheritable Class QueueSurrogate
        Implements ISerializationSurrogate
        ' Methods
        Friend Sub New()
        End Sub

        Private Sub System.Runtime.Serialization.ISerializationSurrogate.GetObjectData(ByVal obj As Object, ByVal info As SerializationInfo, ByVal context As StreamingContext) Implements ISerializationSurrogate.GetObjectData
            Dim objArray As Object() = DirectCast(obj, Queue).ToArray
            If (objArray.Length = 1) Then
                info.AddValue("item", objArray(0))
            Else
                info.AddValue("items", objArray)
            End If
            info.SetType(GetType(QRef))
        End Sub

        Private Function System.Runtime.Serialization.ISerializationSurrogate.SetObjectData(ByVal obj As Object, ByVal info As SerializationInfo, ByVal context As StreamingContext, ByVal selector As ISurrogateSelector) As Object Implements ISerializationSurrogate.SetObjectData
            Return Nothing
        End Function


        ' Nested Types
        <Serializable> _
        Private NotInheritable Class QRef
            Implements IObjectReference, IDeserializationCallback
            ' Methods
            Private Sub System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(ByVal sender As Object) Implements IDeserializationCallback.OnDeserialization
                If (Not Me.queue Is Nothing) Then
                    If (Not Me.items Is Nothing) Then
                        Dim i As Integer
                        For i = 0 To Me.items.Count - 1
                            Me.queue.Enqueue(Me.items.Item(i))
                        Next i
                    Else
                        Me.queue.Enqueue(Me.item)
                    End If
                    Me.queue = Nothing
                End If
            End Sub

            Private Function System.Runtime.Serialization.IObjectReference.GetRealObject(ByVal context As StreamingContext) As Object Implements IObjectReference.GetRealObject
                If (Me.queue Is Nothing) Then
                    Me.queue = New Queue
                End If
                Return Me.queue
            End Function


            ' Fields
            <OptionalField> _
            Private item As Object
            <OptionalField> _
            Private items As IList
            <NonSerialized> _
            Private queue As Queue
        End Class
    End Class
End Namespace

